/*****************************
    carousel for mobile web
    by chenzhian.
******************************/
/*
	在.carousel容器中添加 data-role="carousel"和data-infinite=true/false即可绑定
    Example:
    <div class="carousel slide" data-role="carousel" data-infinite=true>
        <!-- Indicators -->
        <ol class="carousel-indicators">
            <li data-target="#carousel_banner" data-slide-to="0" class="active"></li>
            <li data-target="#carousel_banner" data-slide-to="1"></li>
        </ol>
        <!-- Wrapper for slides -->
        <div class="carousel-inner">
            <div class="item active"><img src="images/banner.jpg" /></div>
            <div class="item"><img src="images/banner2.jpg" /></div>      
        </div>
    </div>
*/
window.mylib = {};
function extMylib(lib, fnName, fn) {
    window.lib = lib || {};
    lib[fnName] = fn;
}
(function ($) {
    "use strict";

    // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
    // ============================================================

    function transitionEnd() {
        var el = document.createElement('bootstrap')

        var transEndEventNames = {
            'WebkitTransition': 'webkitTransitionEnd'
		, 'MozTransition': 'transitionend'
		, 'OTransition': 'oTransitionEnd otransitionend'
		, 'transition': 'transitionend'
        }

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return { end: transEndEventNames[name] }
            }
        }
    }

    // http://blog.alexmaccaw.com/css-transitions
    $.fn.emulateTransitionEnd = function (duration) {
        var called = false, $el = this
        $(this).one($.support.transition.end, function () { called = true })
        var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
        setTimeout(callback, duration)
        return this
    }

    $(function () {
        $.support.transition = transitionEnd()
    })

})(Zepto);

(function ($) {
    //action : "next" or "prev" or num
    $.fn.carousel = function (action, selfRun, callback) {
        var actTermi = {
            next: "left",
            prev: "right"
        };
        var $this = this;
        var $item_set = $this.find(".item");
        var $act = $this.find(".carousel-inner .active");
        var $indicator = $this.find(".carousel-indicators");
        var indx;
        var $expect;
        var dir;
        if ($this.data("status") === "busy") { return; }
        if (typeof action === "number") {
            $expect = $item_set.eq(action);
            dir = "next";
        } else {
            $expect = (action === "next") ? $act.next() : $act.prev();
            dir = action;
        }
        //var $expect = (typeof action === "number") ? $item_set.eq(action) : (action === "next") ? $act.next() : $act.prev();
        if ($expect.length == 0) {
            //console.log($expect.length);
            $expect = (action === "next") ? $item_set.first() : $item_set.last();
        }
        if ($expect.hasClass("active")) { return; }
        $this.data("status", "busy");

        //添加next or prev 样式
        $expect.addClass(dir);
        //执行动画
        if (selfRun) {
            $expect[0].offsetWidth; // force reflow
        }

        $expect.addClass("toActive");
        $act.addClass(actTermi[dir]);
        //更新指示器的点的位置
        indx = $item_set.index($expect);
        $indicator.find('.active').removeClass('active');
        $indicator.children().eq(indx).addClass('active');
        //等待css动画完成
        $act.one($.support.transition.end, function () {
            $act.removeClass(['active', actTermi[dir]].join(' '));
            $expect.removeClass(['toActive', dir].join(' ')).addClass("active");
            $this.data("status", "");
            if (typeof callback === "function") { callback(); }
        });

    }
})(Zepto);

(function ($, window, undefined) {
    // Simple way to check if some form of pointerevents is enabled or not
    window.PointerEventsSupport = false;
    if (window.PointerEvent || window.navigator.msPointerEnabled) {
        window.PointerEventsSupport = true;
    }

    function swipeIt(obj, selfRun) {
        var that = this;
        var pointerDownName = 'MSPointerDown';
        var pointerUpName = 'MSPointerUp';
        var pointerMoveName = 'MSPointerMove';
        if (window.PointerEvent) {
            pointerDownName = 'pointerdown';
            pointerUpName = 'pointerup';
            pointerMoveName = 'pointermove';
        }
        this.obj = obj;
        this.startX;
        this.startY;
        this.nowX = 0;
        this.nowY = 0;
        this.maxX = 0;
        this.maxY = 0;
        this.distX;
        this.distY;
        this.direction;
        //是否执行手动滑动
        this.bIsSwipe = false;
        //手动时是否已有需要执行的动作在排队
        this.isAnimating = false;
        //用于等待css动画结束
        this.bIsDurTrains = false;
        this.imgW = $(obj).width();//图片宽度
        this.$act;
        this.$actFlow;
        this.interval;

        // Shim for requestAnimationFrame from Paul Irishpaul ir
        // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
        this.requestAnimFrame = (function () {
            return window.requestAnimationFrame ||
                    window.webkitRequestAnimationFrame ||
                    window.mozRequestAnimationFrame ||
                    function (callback) {
                        window.setTimeout(callback, 1000 / 60);
                    };
        })().bind(window);

        //事件handler
        // Handle the start of gestures
        this.eTouchstart = function (e) {
            if (window.PointerEventsSupport) {
                document.addEventListener(pointerMoveName, this.eTouchmove, true);
                document.addEventListener(pointerUpName, this.eTouchEnd, true);
            } else {
                document.addEventListener('touchmove', this.eTouchmove, true);
                document.addEventListener('touchend', this.eTouchEnd, true);
                document.addEventListener('mousemove', this.eTouchmove, true);
                document.addEventListener('mouseup', this.eTouchEnd, true);
            }

            var oTouch = e.touches ? e.touches[0] : e;

            //如果没有进行左右滑动,则初始化
            !this.bIsSwipe && this.fSwipeStart(oTouch);
            clearInterval(this.interval);
        }.bind(this);

        // Handle move gestures
        this.eTouchmove = function (e) {
            if (this.bIsDurTrains) { return; }
            var oTouch = e.touches ? e.touches[0] : e;

            this.nowX = oTouch.screenX;
            this.nowY = oTouch.screenY;
            this.distX = this.nowX - this.startX;
            this.distY = this.nowY - this.startY;
            //如果没正在进行滑动,则进行监测
            if (!this.bIsSwipe && this.maxY < 15) {
                this.bIsSwipe = this.fCheckTouch(this.obj);
            }
            //滑动
            //this.bIsSwipe && this.fSwiping(e);
            if (!this.bIsSwipe) { return; }
            e.preventDefault();
            if (this.isAnimating) { return; }
            this.isAnimating = true;
            var that = this;
            this.requestAnimFrame(function () {
                that.fSwiping(e);
            });

        }.bind(this);

        // Handle end gestures
        this.eTouchEnd = function (e) {
            if (window.PointerEventsSupport) {
                document.removeEventListener(pointerMoveName, this.eTouchmove, true);
                document.removeEventListener(pointerUpName, this.eTouchmove, true);
            } else {
                document.removeEventListener('touchmove', this.eTouchmove, true);
                document.removeEventListener('touchend', this.eTouchEnd, true);
                document.removeEventListener('mousemove', this.eTouchmove, true);
                document.removeEventListener('mouseup', this.eTouchEnd, true);
            }

            //关闭左右滑动状态
            this.fSwipeEnd(obj);
            this.bIsSwipe = false;

            if (this.interval) {
                this.interval = setInterval(function () {
                    $(obj).carousel("next", true);
                }, 5000);
            }
        }.bind(this);
        //----init:----//
        //event bind:
        if (window.PointerEventsSupport) {
            //Pointer Event Listeners
            obj.addEventListener(pointerDownName, this.eTouchstart, true);

        } else {
            //Touch Listeners
            obj.addEventListener('touchstart', this.eTouchstart, true);
            //Mouse Listeners
            obj.addEventListener('mousedown', this.eTouchstart, true);
        }
        if (selfRun) {
            this.interval = setInterval(function () {
                $(obj).carousel("next", true);
            }, 5000);
        }
        //----init END----//

    }
    swipeIt.prototype = {
        //初始化
        fSwipeStart: function (oTouch) {
            this.nowX = 0, this.nowY = 0, this.maxX = 0, this.maxY = 0;
            this.startX = oTouch.screenX;
            this.startY = oTouch.screenY;
        },
        //滑动执行
        fSwiping: function (e) {
            if (!this.isAnimating) { return; }

            var distX = this.distX;
            var imgW = this.imgW;
            var iW;
            if (distX > 0) {
                //右滑动
                iW = (distX - imgW) / imgW * 100;
            } else {
                //左滑动
                iW = (imgW + distX) / imgW * 100;
            }
            var pec = distX / imgW * 100

            var actValue = 'translate3d(' + pec + '%,0,0)';
            var actFlowValue = 'translate3d(' + iW + '%,0,0)';
            this.$act.css({
                '-webkit-transform': actValue,
                '-moz-transform': actValue
            });
            this.$actFlow.css({
                '-webkit-transform': actFlowValue,
                '-moz-transform': actFlowValue
            });
            this.isAnimating = false;
        },
        //结束
        fSwipeEnd: function (obj) {
            this.isAnimating = false;
            var that = this;
            var $act = this.$act;
            var $actFlow = this.$actFlow;
            if (this.bIsSwipe) {
                $act.removeClass("manal").removeAttr("style");
                $actFlow.removeClass("manal").removeAttr("style");
                $(obj).carousel(this.direction);

                this.bIsDurTrains = true;
                $act.one($.support.transition.end, function () {
                    that.bIsDurTrains = false;
                })
            }

        },
        swipeInit: function (obj) {
            this.$act = $(obj).find(".carousel-inner .active");
            this.$act.addClass("manal");
            if (this.distX > 0) {
                //右滑动,动画左移
                this.direction = "prev";
            } else {
                //左滑动
                this.direction = "next";
            }
            this.$actFlow = this.fGetFlowSlide(this.$act, this.direction);
            this.$actFlow.addClass("manal " + this.direction);
        },
        //监测是否左右滑动
        fCheckTouch: function (obj) {
            this.maxY = this.maxY > Math.abs(this.distY) ? this.maxY : Math.abs(this.distY);
            var abs_distX = Math.abs(this.distX);
            if (abs_distX > 2 && abs_distX > (this.maxY)) {
                this.swipeInit(obj);
                //初始化后重置触摸起点,避免突然跳动
                this.startX = this.nowX;
                this.distX = 0;
                return true;
            } else {
                return false;
            }
        },
        fGetFlowSlide: function (act, direction) {
            var $expect;
            //获取下一个
            if (direction == "next") {
                $expect = $(act).next();
            } else {
                $expect = $(act).prev();
            }
            //如果没有下一个,则调第一个
            if ($expect.length != 0) {
                return $expect;
            } else if (direction == "next") {
                return $(act).parent().find(".item").first();
            } else {
                return $(act).parent().find(".item").last();
            }
        }

    };
    extMylib(window.mylib, "swipe", swipeIt);
})(Zepto, window, undefined);

/*Init:*/
(function ($) {
    $("[data-role=carousel]").each(function (i, item) {
        var bIsInfinite = $(item).data("infinite");
        new mylib.swipe(item, bIsInfinite);
    });

    $(document).on("click", ".carousel-indicators>li", function (e) {
        //暂停循环
        //var $container = $(this).parents(".carousel");
        //$container.data("status","busy");
        var $this = $(this);
        var tar = $this.data("target");
        var ind = parseInt($this.data("slide-to"));
        $(tar).carousel(ind, true);

    });

    //$(obj).carousel("next", true);

})(Zepto);

//左下角浮动的导航按钮点击事件
(function ($) {
    $(document).ready(function () {
        $(".icon4-qqt").click(function () {
            $(this).parent().toggleClass("expand");
            $(".bgFilter").toggleClass("filterHide");
        });
        $(".bgFilter").click(function () {
            $(this).toggleClass("filterHide");
            $(".qqtPlus").toggleClass("expand");
        });
    });
})(Zepto);